package com.gzhryc.shared_device.common.payment.services;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.common.payment.dao.AppConfigDao;
import com.gzhryc.shared_device.common.payment.dao.db.AppConfig;

import java.sql.SQLException;
import java.util.Date;

public class AppConfigService {

    static Logger log = Logger.getLogger(AppConfigService.class);

    public static AppConfigService self() {
        return MultiDBTools.getService(AppConfigService.class, true);
    }

    public static AppConfigService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, AppConfigService.class, true);
    }

    AppConfigDao dao;

    public AppConfigService(String jdbcKey) {
        this.dao = new AppConfigDao(jdbcKey);
    }

    public AppConfig getByKeys(String appId,Integer type){
        if(StringTools.isNotBlank(appId) && type != null){
            Conditions conditions = new Conditions(AppConfig.class);
            conditions.and().is("appId",appId);
            conditions.and().is("type",type);
            try {
                return dao.get(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public boolean save(AppConfig appConfig) throws LogicException {
        AppConfig temp = getByKeys(appConfig.getAppId(),appConfig.getType());
        if(temp != null){
            Conditions conditions = new Conditions(AppConfig.class);
            conditions.and().is("appId",appConfig.getAppId());
            conditions.and().is("type",appConfig.getType());

            try {
                return dao.updateNotNull(appConfig,conditions) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }else{
            appConfig.setCreateDate(new Date());
            try {
                return dao.insert(appConfig) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean deleteByKeys(String appId,Integer type) {
        if (StringTools.isNotBlank(appId) && type != null) {
            Conditions conditions = new Conditions(AppConfig.class);
            conditions.and().is("appId", appId);
            conditions.and().is("type", type);
            try {
                return dao.deleteByCondition(conditions) >= 0;
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return false;
    }

}
